package com.huitone.smspfm.oldclient.asclient;


import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.huitone.smspfm.oldclient.logger.ExtLogger;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.core.FileWriter;
import com.huitone.smspfm.oldclient.model.RespSms;
import com.huitone.smspfm.oldclient.store.MtTmpStore;
import com.huitone.smspfm.socket.core.handler.DefaultMessageHandler;
import com.huitone.smspfm.socket.core.net.ExtSocket;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.ActiveTestResp;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Submit2Resp;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;

/**   
* @Title ClientMessageHandler.java 
* @Package com.huitone.smspfm.oldclient.core 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年3月31日 上午11:46:47 
* @version V1.0   
*/
public class ClientMessageHandler extends DefaultMessageHandler {
	
	private static final ExtLogger logger = ExtLogger.create(ClientMessageHandler.class);
	
	private FileWriter writer = null;
	
	private final ExecutorService executorService = new ThreadPoolExecutor(AppStaticConfigs.chExcutorPoolSize, 
			AppStaticConfigs.chExcutorPoolSize, 1L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(AppStaticConfigs.chExcutorPoolSize), new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			boolean offer = false;
			while(!executor.isShutdown() && !offer) {
				offer = executor.getQueue().offer(r);
				if (!offer) {
					try {
						TimeUnit.MILLISECONDS.sleep(100);
					} catch (InterruptedException e) {}
				}
			}
		}
	});
	
	@Override
	public void handleSubmit2RespMessage(Head head, Submit2Resp body, ExtSocket socket) {
		
		executorService.execute(new Runnable() {
			
			@Override
			public void run() {
				
				logger.resp(new Message(head, body).toString());
				
				String serialNo = head.getSerialNo();
				
				// 移除临时Map缓存的数据
				MtTmpStore.remove(serialNo);
				
				RespSms respSms = new RespSms();
				respSms.setClientname(StringUtils.toString(body.getOrgSrvNode()));
				respSms.setMobileno(StringUtils.toString(body.getUserNumber()));
				respSms.setSendport(extractSendport(StringUtils.toString(body.getSendPort())));
				respSms.setSendtime(DateTimeUtils.dateToStr2(new Date()));
				respSms.setNewSerialNo(StringUtils.toString(serialNo));
				respSms.setSrvNode(StringUtils.toString(body.getSrvNode()));
				respSms.setServiceCode(StringUtils.toString(body.getServiceCode()));
				respSms.setErrorCode(StringUtils.toString(body.getResult()));
				
				List<String> orgSerialNos = StringUtils.splitToList(StringUtils.toString(body.getOrgSerialNo()), ",");
				
				for (String orgSerialNo:orgSerialNos) {
					if (!StringUtils.isEmpty(orgSerialNo)) {
						respSms.setSerialno(orgSerialNo);
						try {
							if (writer != null) {
								writer.write(respSms);
							} else {
								logger.warn("FileWrite为空,打印数据:" + respSms.toString());
							}
						} catch (IOException e) {
							logger.error("写Submit2Resp信息异常,Resp信息:" + respSms.toString(), e);
						}
					}
				}
			}
		});
	}
	
	@Override
	public void handleActiveTestRespMessage(Head head, ActiveTestResp body, ExtSocket socket) {
	}
	
	private String extractSendport(String sendport) {
		
		for (int i = 0 ; i < AppStaticConfigs.rspSpExtractRegexs.size() ; i ++) {
			Pattern p = Pattern.compile(AppStaticConfigs.rspSpExtractRegexs.get(i));
			Matcher m = p.matcher(sendport);
			if (m.find()) {
				int groupCount = m.groupCount();
				int extractGroupIndex = AppStaticConfigs.rspSpExtractRegexsMappingGroup.get(i);
				if (extractGroupIndex <= groupCount) {
					sendport = m.group(extractGroupIndex);
					break;
				}
			}
		}
		
		return sendport;
	}
	
	public FileWriter getWriter() {
		return writer;
	}

	public void setWriter(FileWriter writer) {
		this.writer = writer;
	}

	@Override
	public void destroy() {
		
		if (executorService != null && !executorService.isShutdown()) {
			executorService.shutdown();
		}
		
		if (writer != null) {
			writer.destroy();
		}
	}
}
